<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import { onMounted, ref, unref } from 'vue';
import { useRoute } from 'vue-router';

import { useFs } from '@fast-crud/fast-crud';

import { ExtendNoticeApi } from '#/api/basic/msg/extendNotice';
import { ActionEnum } from '#/enums/commonEnum';
import { $t } from '#/locales';

import { createCrudOptions } from './data/crud';

defineOptions({
  name: '查看我的消息',
  inheritAttrs: false,
});
const { crudBinding } = useFs({ createCrudOptions });

const type = ref<
  ActionEnum.ADD | ActionEnum.COPY | ActionEnum.EDIT | ActionEnum.VIEW
>(ActionEnum.ADD);
const typeFormRef = ref<
  ActionEnum.ADD | ActionEnum.COPY | ActionEnum.EDIT | ActionEnum.VIEW
>(ActionEnum.ADD);
const formRef = ref();
const route = useRoute();

const load = async (data: Recordable) => {
  type.value = data?.type;
  typeFormRef.value = data?.type;

  if ([ActionEnum.COPY].includes(unref(type))) {
    typeFormRef.value = ActionEnum.ADD;
  }

  if (![ActionEnum.ADD].includes(unref(type))) {
    const record = await ExtendNoticeApi.get(data?.id);
    record.id = undefined;
    formRef.value.setFormData(record, { mergeForm: false });
  }
};

onMounted(async () => {
  const { params } = route;
  if (params?.id) {
    load({ type: params?.type, id: params?.id });
  }
});

defineExpose({ load });
</script>

<template>
  <FsPage>
    <template #header>
      <div class="title">{{ $t(`common.title.${type}`) }}</div>
    </template>
    <div class="p-5">
      <FsForm ref="formRef" v-bind="crudBinding[`${typeFormRef}Form`]" />
    </div>
  </FsPage>
</template>
